/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.love.cloud.auth.config;

import com.love.cloud.auth.service.impl.MyUserDetailsServiceImpl;
import com.love.cloud.auth.tokengranter.DingFreeLoginCustomTokenGranter;
import com.love.cloud.auth.tokengranter.DingIdCustomTokenGranter;
import com.love.cloud.auth.tokengranter.PhoneOpenCodeCustomTokenGranter;
import com.love.cloud.auth.tokengranter.QRCodeCustomTokenGranter;
import com.love.cloud.common.core.constant.SecurityConstants;
import com.love.cloud.common.security.component.MyWebResponseExceptionTranslator;
import com.love.cloud.common.security.service.PigClientDetailsService;
import com.love.cloud.common.security.service.MyUser;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;
import java.util.*;

/**
 * @author lengleng
 * @date 2019/2/1 认证服务器配置
 */
@RequiredArgsConstructor
@EnableAuthorizationServer
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	private final DataSource dataSource;

	private final MyUserDetailsServiceImpl userDetailsService;

	private final AuthenticationManager authenticationManager;

	private final TokenStore tokenStore;

	@Override
	@SneakyThrows
	public void configure(ClientDetailsServiceConfigurer clients) {
		PigClientDetailsService clientDetailsService = new PigClientDetailsService(dataSource);
		clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
		clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
		clients.withClientDetails(clientDetailsService);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		//加入自定义的 TokenGranter
		List<TokenGranter> tokenGranters = getTokenGranters(authenticationManager,endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory());
		//添加原来的转化器
		tokenGranters.add(endpoints.getTokenGranter());
		//设置自定义转换器
		DefaultAccessTokenConverter defaultAccessTokenConverter=new DefaultAccessTokenConverter();
		defaultAccessTokenConverter.setUserTokenConverter(new MyUserAuthenticationConverter());
		endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST).tokenStore(tokenStore)
				.tokenEnhancer(tokenEnhancer()).userDetailsService(userDetailsService)
				.accessTokenConverter(defaultAccessTokenConverter)
				.authenticationManager(authenticationManager).reuseRefreshTokens(false)
				.tokenGranter(new CompositeTokenGranter(tokenGranters))
				.pathMapping("/oauth/confirm_access", "/token/confirm_access")
				.exceptionTranslator(new MyWebResponseExceptionTranslator());

	}

//	@Bean
//	public TokenStore tokenStore() {
//		RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
//		tokenStore.setPrefix(CacheConstants.PROJECT_OAUTH_ACCESS);
//		//设置自定义token生成的规则
//		CustomAuthenticationKeyGenerator customAuthenticationKeyGenerator=new CustomAuthenticationKeyGenerator();
//		tokenStore.setAuthenticationKeyGenerator(customAuthenticationKeyGenerator);
//		return tokenStore;
//	}

	@Bean
	public TokenEnhancer tokenEnhancer() {
		return (accessToken, authentication) -> {
			final Map<String, Object> additionalInfo = new HashMap<>(16);
			if(authentication.getUserAuthentication()!=null){
				MyUser myUser = (MyUser) authentication.getUserAuthentication().getPrincipal();
				additionalInfo.put(SecurityConstants.DETAILS_LICENSE, SecurityConstants.PROJECT_LICENSE);
				additionalInfo.put(SecurityConstants.DETAILS_USER_ID, myUser.getId());
				additionalInfo.put(SecurityConstants.DETAILS_USERNAME, myUser.getUsername());
				//additionalInfo.put(SecurityConstants.DETAILS_DEPT_INFO, sosUser.getDeptList());
				//additionalInfo.put(SecurityConstants.DETAILS_USERINFO, sosUser.getUserInfo());
				((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
			}
			return accessToken;
		};
	}

	/**
	 * 获取到自定义的token授权者
	 * @param authenticationManager
	 * @param tokenServices
	 * @param clientDetailsService
	 * @param requestFactory
	 * @return
	 */
	private List<TokenGranter> getTokenGranters(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
		return new ArrayList<>(Arrays.asList(
				new PhoneOpenCodeCustomTokenGranter(authenticationManager,tokenServices, clientDetailsService, requestFactory),
				new QRCodeCustomTokenGranter(authenticationManager,tokenServices, clientDetailsService, requestFactory),
				new DingIdCustomTokenGranter(authenticationManager,tokenServices, clientDetailsService, requestFactory),
				new DingFreeLoginCustomTokenGranter(authenticationManager,tokenServices, clientDetailsService, requestFactory)
		));
	}

}
